package com.jhgsys.internal.sypq.controller;


import com.alibaba.excel.util.DateUtils;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.authentication.ShiroHelper;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.sypq.entity.*;
import com.jhgsys.internal.sypq.service.*;
import com.jhgsys.internal.system.entity.User;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * 任务管理 Controller
 *
 * @author ganjun
 * @date 2024-11-18 10:06:38
 */
@Slf4j
@Validated
@Controller
public class ScheduleController extends BaseController {

    @Autowired
    private IScheduleService scheduleService;
    @Autowired
    private ShiroHelper shiroHelper;


    @GetMapping(FebsConstant.VIEW_PREFIX + "schedule")
    @RequiresPermissions("schedule:view")
    public ModelAndView scheduleIndex(@RequestParam(name = "projectCode", required = false, defaultValue = "") String projectCode) {
        //获取最晚完成时间
        String viewPath = jumpPage("sypq/schedule/scheduleList");
        ModelAndView modelAndView = new ModelAndView(viewPath);
        modelAndView.addObject("projectCode", projectCode);
        modelAndView.addObject("isAdmin", isAdmin());
        User user = (User) getSubject().getPrincipal();
        modelAndView.addObject("userid", user.getUserId());
        AuthorizationInfo authorizationInfo = shiroHelper.getCurrentuserAuthorizationInfo();
        modelAndView.addObject("permissions", authorizationInfo.getStringPermissions());
        return modelAndView;

    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "schedule/updateSchedule/{id}")
    @RequiresPermissions(value = {"schedule:audit", "schedule:edit"}, logical = Logical.OR)
    public String scheduleUpdate(Model model, @PathVariable("id") String id) {
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskCode(id);
        List<TaskDto> list = scheduleService.getAssembledTask(taskDto);
        TaskDto schedule = new TaskDto();
        if (list.size() > 0) {
            schedule = list.get(0);
        }
        model.addAttribute("schedule", schedule);
        model.addAttribute("type", "edit");
        return jumpPage("sypq/schedule/scheduleEdit");
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "schedule/detail/{id}")
    @RequiresPermissions("schedule:detail")
    public String scheduledeDetail(Model model, @PathVariable("id") String id) {
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskCode(id);
        List<TaskDto> list = scheduleService.findTaskList(taskDto);
        TaskDto schedule = new TaskDto();
        if (list.size() > 0) {
            schedule = list.get(0);
        }
        model.addAttribute("type", "detail");
        model.addAttribute("schedule", schedule);
        return jumpPage("sypq/schedule/scheduleDetail");
    }

    @RequestMapping(value = "schedule/list", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    //@RequiresPermissions("schedule:view")
    public Map scheduleList(TaskDto taskDto) {
        boolean isAdmin = isAdmin();
        List<ScheduleDto> list=this.scheduleService.findTaskPage(taskDto, isAdmin);
        //显示审批未通过的原因
        StringBuffer  reason=new StringBuffer();
        int i=0;
        for(ScheduleDto scheduleDto:list){
          List<TaskDto> taskDtoList=   scheduleDto.getTaskList();
          for(TaskDto obj:taskDtoList){
              if(3==obj.getStatus()){
                  if(i>0){
                      reason.append("\n");
                  }
                  reason.append(obj.getTaskCode()+"任务排期审核未通过，原因:"+obj.getReason()+",请及时修改！");
                  i++;
              }
          }
        }
        Map  map=new HashMap();
        map.put("list",list);
        map.put("reason",reason.toString());
        return map;
    }

    @GetMapping(value = "schedule/oneKeyAssemblie")
    @ResponseBody
    @RequiresPermissions("schedule:oneKeyAssemblie")
    public FebsResponse oneKeyAssemblie(TaskDto taskDto) throws FebsException {
        try {
            boolean isAdmin = isAdmin();
            this.scheduleService.oneKeyAssemblie(taskDto, isAdmin);
            return success();
        } catch (Exception ex) {
            return failure(ex, "排期失败");
        }
    }

    @Log("修改排期")
    @PostMapping("schedule/update")
    @ResponseBody
    @RequiresPermissions("schedule:edit")
    public FebsResponse updateSchedule(@RequestBody TaskDto taskDto) {
        try {
            this.scheduleService.updateSchedule(taskDto);
            return success();
        } catch (Exception ex) {
            return failure(ex, "修改失败");
        }
    }


    @Log("提交审批")
    @PostMapping("schedule/commit")
    @ResponseBody
    @RequiresPermissions("schedule:commit")
    public FebsResponse commit(@RequestBody TaskDto taskDto) throws FebsException {
        try {
            this.scheduleService.commit(taskDto);
            return success();
        } catch (Exception ex) {
            return failure(ex, "提交失败");
        }
    }


    @Log("批量提交审批")
    @GetMapping("schedule/batchCommit")
    @ResponseBody
    @RequiresPermissions("schedule:commit")
    public FebsResponse batchCommit(TaskDto taskDto) throws FebsException {
        try {
            taskDto.setStatus(1);
            taskDto.setTaskType(1);
            Boolean isAdmin = isAdmin();
            this.scheduleService.batchCommit(taskDto, isAdmin);
            return success();
        } catch (Exception ex) {
            return failure(ex, "提交失败");
        }
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "schedule/audit/{id}")
    @RequiresPermissions("schedule:audit")
    public String sypqProjectDetail(Model model, @PathVariable("id") String id) {
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskCode(id);
        List<TaskDto> list = scheduleService.getAssembledTask(taskDto);
        TaskDto schedule = new TaskDto();
        if (list.size() > 0) {
            schedule = list.get(0);
        }

        model.addAttribute("schedule", schedule);
        model.addAttribute("type", "aduit");
        return jumpPage("sypq/schedule/scheduleEdit");
    }


    @Log("审批")
    @ResponseBody
    @PostMapping(value = "schedule/audit")
    @RequiresPermissions("schedule:audit")
    public FebsResponse saveAudit(@RequestBody WorkflowRecord workflowRecord) throws FebsException {
        try {
            this.scheduleService.saveAudit(workflowRecord);
            return success();
        } catch (Exception ex) {
            return failure(ex, "修改失败");
        }
    }


    @Log("批量审批")
    @ResponseBody
    @GetMapping(value = "schedule/batchAudit")
    @RequiresPermissions("schedule:audit")
    public FebsResponse batchAudit() throws FebsException {
        try {
            TaskDto taskDto = new TaskDto();
            taskDto.setStatus(2);
            taskDto.setDeletedFlg("0");
            this.scheduleService.batchAudit(taskDto, isAdmin());
            return success();
        } catch (Exception ex) {
            return failure(ex, "修改失败");
        }
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "schedule/dialog/{taskcode}")
    public String openDialog(Model model, @PathVariable("taskcode") String taskcode) {
        model.addAttribute("taskcode", taskcode);
        return jumpPage("sypq/schedule/scheduleDialog");
    }

    //删除排期
    @GetMapping("schedule/delete/{id}")
    @ResponseBody
    @RequiresPermissions("schedule:delete")
    public FebsResponse deleteSchedule(@PathVariable("id") String taskcode) throws FebsException {
        try {
            scheduleService.deleteSchedule(taskcode,1);
            return success();
        } catch (Exception ex) {
            return failure(ex, "删除失败");
        }
    }

    @GetMapping("schedule/excel")
    @ResponseBody
    @RequiresPermissions("schedule:excel")
    public void export(TaskDto taskDto, HttpServletResponse response) throws FebsException {
        try {
            List<TaskDto> list = this.scheduleService.findExcelList(taskDto);
            ExcelKit.$Export(TaskExcelDto.class, response).downXlsx(list, true);
        } catch (Exception e) {
            String message = "导出Excel失败";
            e.printStackTrace();
            log.error(message, e);
            throw new FebsException(message);
        }
    }


    @GetMapping("schedule/taskTestList")
    @ResponseBody
    public List<TaskTestDto> getTaskTestList(@RequestParam("rsCode") String rscode) {
        return this.scheduleService.getTaskTestList(rscode);
    }

    @GetMapping("schedule/taskTestExcel")
    @ResponseBody
    @RequiresPermissions("schedule:taskTestExcel")
    public void taskTestExport(@RequestParam("rsCode") String rscode, HttpServletResponse response) throws FebsException {
        try {
            List<TaskTestDto> list = this.scheduleService.getTaskTestList(rscode);
            ExcelKit.$Export(TaskTestDto.class, response).downXlsx(list, true);
        } catch (Exception e) {
            String message = "导出Excel失败";
            e.printStackTrace();
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("schedule/check")
    @ResponseBody
    public FebsResponse check(@RequestParam("taskCode") String taskCode,
                              @RequestParam("planStartdate") String planStartdate,
                              @RequestParam("planStarttime") String planStarttime,
                              @RequestParam("planEnddate") String planEnddate,
                              @RequestParam("planEndtime") String planEndtime) {
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskCode(taskCode);
        taskDto.setPlanStartdate(DateUtil.parseDate(planStartdate, "yyyy-MM-dd"));
        taskDto.setPlanStarttime(DateUtil.parseDate(planStarttime, "HH:mm:dd"));
        taskDto.setPlanEnddate(DateUtil.parseDate(planEnddate, "yyyy-MM-dd"));
        taskDto.setPlanEndtime(DateUtil.parseDate(planEndtime, "HH:mm:dd"));
        String result = this.scheduleService.checkTask(taskDto);
        return new FebsResponse().success().data(result);
    }

    @GetMapping("schedule/getMinPlanDate")
    @ResponseBody
    public FebsResponse getStartDate(@RequestParam("taskCode") String taskCode) {
        Date minPlanDate = this.scheduleService.getMinPlanDate(taskCode);
        return new FebsResponse().success().data(DateUtils.format(minPlanDate,"yyyy-MM-dd"));
    }


    @GetMapping("schedule/getMaxPlanEnddate")
    @ResponseBody
    public FebsResponse getMaxPlanEnddate() {
        Date maxPlanDate = this.scheduleService.getMaxPlanEnddate();
        return new FebsResponse().success().data(DateUtils.format(maxPlanDate,"yyyy-MM-dd"));
    }



}
